import React from 'react';
import { inject, observer } from 'mobx-react';
import './index.less';

@inject('store')
@observer
class Code extends React.Component {
	constructor(props) {
		super(props);
		this.state = {

			code: '',

		};
	}
	componentDidMount() {
		this.initCode()

	}
	initCode() {
		const code = this.getCode();
		this.props.store.project.code = code;
		this.setState({ code }, () => {
			document.querySelectorAll("pre code").forEach(block => {
				try {
					window.hljs.highlightBlock(block);
				}
				catch (e) { console.log(e); }
			});
		})
	}
	getTests(tests) {
		let code = ''
		tests.forEach(test => {
			code += `it('${test.title}', async () => {${this.getEvents(test.events)}
    },30000)
	`
		})
		return code;

	}
	getEvents(events) {
		let code = ''
		events.forEach(event => {
			code += `
        var elements = await page.$$('.${event.selectElement.className}')
        var element = elements[${event.selectElement.index}];
        await page.waitFor(500)
        var err = await element['${event.eventType}']('${event.params.split(',')}');
        await page.waitFor(500)
        if(err) throw Error('${event.identify}执行${event.eventType}失败，错误日志：',err);
        await page.waitFor(500)
			`
		})
		return code;
	}
	getCode() {
		let proStore = this.props.store.project;
		proStore = JSON.parse(JSON.stringify(proStore))
		const project = proStore.projects[proStore.projectActive];
		if (!project) return;
		const page = project.pages[proStore.pageActive];
		const code =
			`
const automator = require('miniprogram-automator')
describe('${page.pageName}', () => {
    let miniProgram
    let page

    beforeAll(async () => {
        miniProgram = await automator.launch({
        projectPath: '${project.path}'
        })
        page = await miniProgram.reLaunch('${page.pagePath}')
        await page.waitFor(500)
    }, 30000)

    ${this.getTests(page.tests)}
    afterAll(async () => {
        await miniProgram.close()
    })
})
`
		return code;
	}


	render() {
		const { code = "hello workd" } = this.state;
		const project = this.props.store.project;
		const { projects, projectActive } = project;
		const projectName = projects[projectActive].projectName
		return (
			<div className="code-container">
				<div className="code">
					<h3>名称：{projectName}.test.js </h3>
					<pre className="preview"><code>{code}</code></pre>
					{/* <textarea id="textarea" value={code}></textarea> */}
				</div>
			</div>
		);
	}
}

export default Code;
